package zhieasy.cn.xpu_helper.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.model.common.Permission;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.xpu_helper.security.utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DaHang
 * @date 2020/8/13 15:38
 * 用来处理使用token登陆成功的
 */
@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
        , Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        //1.获取用户信息
        WechatUser user = (WechatUser)authentication.getPrincipal();
        //2.生成token
        String token = jwtUtils.generateTokenWithLogin(user,"true",user.getSessionKey());

        //把数据写出去
        Map<String,String> map = new HashMap();
        map.put("token",token);
        map.put("sessionKey",user.getSessionKey());
        map.put("openId",user.getUsername());
        //token,sessionKey
        String str = JSONObject.toJSONString(ResultUtils.success("认证成功",map),
            SerializerFeature.DisableCircularReferenceDetect);
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    /**
     * 组装树
     *
     * @param menuList
     * @param pId
     * @return
     */
    private static List<Permission> makeTree(List<Permission> menuList, Long pId) {
//子类
        List<Permission> children = menuList.stream().filter(x -> x.getParentId() ==
            pId).collect(Collectors.toList());
//后辈中的非子类
        List<Permission> successor = menuList.stream().filter(x -> x.getParentId() !=
            pId).collect(Collectors.toList());
        if (children.size() > 0) {
            children.forEach(x ->
                {
                    if(successor.size() > 0){
                        makeTree(successor, x.getPermissionId()).forEach(
                            y -> x.getChildren().add(y)
                        );
                    }
                }
            );
        }
        return children;
    }
}
